import { asyncRouterMap, constantRouterMap } from '@/router';

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role));
    } else {
        return true;
    }
}

function hasChild (item) {
    return item.children && item.children.length !== 0;
};

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param menus
 */

function filterAsyncRouter (routes, menus) {
    let res = [];
    routes.forEach(item => {
        if (item) {
            let obj = item;
            if (hasChild(item) && menus.includes(item.name) && item.meta.icon) {
                obj.children = filterAsyncRouter(item.children, menus);
            }
            if (menus.includes(item.name)) { res.push(obj); }
        }
    });
    return res;
}

const permission = {
    state: {
        routers: [],
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRouterMap.concat(routers);
        }
    },
    actions: {
        GenerateRoutes ({ commit }, data) {
            return new Promise(resolve => {
                const { menus } = data;
                let accessedRouters;
                // if (roles.includes('admin')) {
                //     accessedRouters = asyncRouterMap;
                // } else {
                //     accessedRouters = filterAsyncRouter(asyncRouterMap, roles);
                // }
                accessedRouters = [...filterAsyncRouter(asyncRouterMap, menus), { path: '*', redirect: '/404', hidden: true }];
                // console.log(accessedRouters);
                commit('SET_ROUTERS', accessedRouters);
                resolve(accessedRouters);
            });
        }
    }
};

export default permission;
